<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="备份文件" prop="fileName">
        <el-input v-model="formData.fileName" disabled />
      </el-form-item>
      <el-form-item label="目标数据库" prop="targetId">
          <el-select
            v-model="formData.targetId"
            placeholder="目标数据库"
          >
            <el-option
              v-for="dict in list"
              :label="dict.connectName"
              :key="dict.id"
              :value="dict.id"
            />
          </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as DataBackupApi from '@/api/infra/dbbackup'

defineOptions({ name: 'DbRestoreForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('恢复数据库') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<DataBackupApi.DbRestoreVO>({
  id: 0,
  fileName: 'jprocms.sql',
  targetId: 0
})
const formRules = reactive({
  id: [{ required: true, message: '原数据库不能为空', trigger: 'blur' }],
  fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  targetId: [{ required: true, message: '目标数据库不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (dbType:string,fileName:string,id: number) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      getDbList(dbType)
      formData.value.id = id
      formData.value.fileName = fileName
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as DataBackupApi.DbRestoreVO
    await DataBackupApi.dbRestore(data)
    message.success(t('common.success'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
/** 查询数据库列表 */
const getDbList = async (dbType:string) => {
  loading.value = true
  try {
    list.value = await DataBackupApi.getDbListByType(dbType)
  } finally {
    loading.value = false
  }
}
</script>
